<?php
function js2PhpTime_($jsdate){
  if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $jsdate, $matches)==1){
	$ret = mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
	//echo $matches[4] ."-". $matches[5] ."-". 0  ."-". $matches[1] ."-". $matches[2] ."-". $matches[3];
  }else if(preg_match('@(\d+)/(\d+)/(\d+)@', $jsdate, $matches)==1){
	$ret = mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]);
	//echo 0 ."-". 0 ."-". 0 ."-". $matches[1] ."-". $matches[2] ."-". $matches[3];
  }
  return $ret;
}

function js2PhpTime($date){
  if(strpos($date, '-')){
   if(preg_match('@(\d+)-(\d+)-(\d+)\s+(\d+):(\d+)@', $date, $matches)==1)
	return mktime($matches[4], $matches[5], 0, $matches[2], $matches[3], $matches[1]);
   else if(preg_match('@(\d+)-(\d+)-(\d+)@', $date, $matches)==1){
	return mktime(0, 0, 0, $matches[2], $matches[3], $matches[1]);
  }
  }else if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $date, $matches)==1){
	return mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
  }else if(preg_match('@(\d+)/(\d+)/(\d+)@', $date, $matches)==1){
   return mktime(0, 0, 0, $matches[2], $matches[3], $matches[1]);
  }else
   return mktime();
 }

function php2JsTime($phpDate){
	//echo $phpDate;
	//return "/Date(" . $phpDate*1000 . ")/";
	return date("m/d/Y H:i", $phpDate);
}

function php2MySqlTime($phpDate){
	return date("Y-m-d H:i:s", $phpDate);
}

function mySql2PhpTime($sqlDate){
	$arr = date_parse($sqlDate);
	return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);

}
?>
<?php
include_once("dbconfig.php");
function addCalendar($st, $et, $sub, $ade){
  $ret = array();
  try{
	$db = new DBConnection();
	$db->getConnection();
	$sql = "insert into `jqcalendar` (`subject`, `starttime`, `endtime`, `isalldayevent`) values ('"
	  .mysql_real_escape_string($sub)."', '"
	  .php2MySqlTime(js2PhpTime($st))."', '"
	  .php2MySqlTime(js2PhpTime($et))."', '"
	  .mysql_real_escape_string($ade)."' )";
	//echo($sql);
		if(mysql_query($sql)==false){
	  $ret['IsSuccess'] = false;
	  $ret['Msg'] = mysql_error();
	}else{
	  $ret['IsSuccess'] = true;
	  $ret['Msg'] = 'add success';
	  $ret['Data'] = mysql_insert_id();
	}
	}catch(Exception $e){
	 $ret['IsSuccess'] = false;
	 $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}


function addDetailedCalendar($st, $et, $sub, $ade, $dscr, $loc, $color, $tz){
  $ret = array();
  try{
	$db = new DBConnection();
	$db->getConnection();
	$sql = "insert into `jqcalendar` (`subject`, `starttime`, `endtime`, `isalldayevent`, `description`, `location`, `color`) values ('"
	  .mysql_real_escape_string($sub)."', '"
	  .php2MySqlTime(js2PhpTime($st))."', '"
	  .php2MySqlTime(js2PhpTime($et))."', '"
	  .mysql_real_escape_string($ade)."', '"
	  .mysql_real_escape_string($dscr)."', '"
	  .mysql_real_escape_string($loc)."', '"
	  .mysql_real_escape_string($color)."' )";
	//echo($sql);
		if(mysql_query($sql)==false){
	  $ret['IsSuccess'] = false;
	  $ret['Msg'] = mysql_error();
	}else{
	  $ret['IsSuccess'] = true;
	  $ret['Msg'] = 'add success';
	  $ret['Data'] = mysql_insert_id();
	}
	}catch(Exception $e){
	 $ret['IsSuccess'] = false;
	 $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function listCalendarByRange($sd, $ed){

	$ret = array();
	$ret['events'] = array();
	$ret["issort"] =true;
	$ret["start"] = php2JsTime($sd);
	$ret["end"] = php2JsTime($ed);
	$ret['error'] = null;
	$start=php2MySqlTime($sd);
	$end=php2MySqlTime($ed);
	try
	{
		$db	 = new DBConnection();
		$db->getConnection();
		$sql	= "SELECT *
		FROM `efdsh_jqcalendar`
		WHERE id_teacher=".$_GET[id]." AND type=1 and StartTime >= '$start' AND EndTime < '$end' ORDER BY StartTime ASC";
		$res = mysql_query($sql);
		
		//span whole week with busy time
		$days=0;
		while($days<7){
			$stime=strtotime(date("Y-m-d",$sd)." 07:00 + $days days");
			$etime=strtotime(date("Y-m-d",$sd)." 23:59 + $days days");
			$ret['events'][] = array(
				0,
				"Optaget",
				//$row->Subject,
				php2JsTime($stime),
				php2JsTime($etime),
				0,
				0,//more than one day event
				//$row->InstanceType,
				1,//Recurring event,
				9,
				0,//editable
				'',
				''//$attends
			);
			$days++;
		}
		$dayidx=array("",0,1,2,3,4,5,6);//7 days, each value is busy idx in events array
		
		while($row = mysql_fetch_object($res))
		{
			if($row->Color==9){
				$stime=mySql2PhpTime($row->StartTime);
				$etime=mySql2PhpTime($row->EndTime);
				$sday=date("N",$stime);
				$tmp=$dayidx[$sday];//get index
				$sbusy=js2PhpTime($ret['events'][$tmp][2]);
				if($stime > $sbusy){//modify busy end time
					$ret['events'][$tmp][3]=php2JsTime($stime);
					//if($sday==8)
					//$ret['dbg'][]=date("Y-m-d H:i",$stime)." ".date("Y-m-d H:i",$sbusy)." : $tmp";
					if($etime < strtotime(date("Y-m-d",$etime)." 23:30")){
						$ret['events'][]= array(
							0,
							"Optaget",
							//$row->Subject,
							php2JsTime($etime),
							php2JsTime(strtotime(date("Y-m-d",$etime)." 23:59")),
							0,
							0,//more than one day event
							//$row->InstanceType,
							1,//Recurring event,
							9,
							0,//editable
							'',
							''//$attends
						);
						$dayidx[$sday]=end(array_keys($ret['events']));//set index
						//$ret['dbg'][]=print_r($dayidx,true);
					}
				}else{
					if($etime < strtotime(date("Y-m-d",$etime)." 23:30")){
						$ret['events'][$tmp][2]=php2JsTime($etime);
						//unset($ret['events'][$sday]);
					}
				}
				continue;
			}
			//*
			$ret['events'][] = array(
				$row->Id,
				"Optaget",
				//$row->Subject,
				php2JsTime(mySql2PhpTime($row->StartTime)),
				php2JsTime(mySql2PhpTime($row->EndTime)),
				$row->IsAllDayEvent,
				0,//more than one day event
				//$row->InstanceType,
				0,//Recurring event,
				9,
				1,//editable
				$row->Location,
				''//$attends
			);
			//*/
		}
	}catch(Exception $e)
	{
		$ret['error'] = $e->getMessage();
	}

	//$ret['events']=array_values($ret['events']);
	return $ret;
}

function mlistCalendarByRange($sd, $ed){

	$ret = array();
	$ret['events'] = array();
	$ret['error'] = null;
	$start=php2MySqlTime($sd);
	$end=php2MySqlTime($ed);
	
	try
	{
		$db	 = new DBConnection();
		$db->getConnection();
		$sql	= "SELECT *
		FROM `efdsh_jqcalendar`
		WHERE id_teacher=".$_GET['id']." AND type=1 and StartTime >= '$start' AND EndTime < '$end' ORDER BY StartTime ASC";
		$res = mysql_query($sql);
		
		//span whole week with busy time
		
			$stime=strtotime(date("Y-m-d",$sd)." 07:00");
			$etime=strtotime(date("Y-m-d",$sd)." 23:59");
			$ret['events'][] = array(
				0,
				"Optaget",
				php2JsTime($stime),
				php2JsTime($etime)
			);
		
		$idx=0;
		while($row = mysql_fetch_object($res))
		{
			if($row->Color==9){
				$stime=mySql2PhpTime($row->StartTime);
				$etime=mySql2PhpTime($row->EndTime);
				$sbusy=js2PhpTime($ret['events'][$idx][2]);
				if($stime > $sbusy){//modify busy end time
					$ret['events'][$idx][3]=php2JsTime($stime);
					if($etime < strtotime(date("Y-m-d",$etime)." 23:30")){
						$ret['events'][]= array(
							0,
							"Optaget",
							php2JsTime($etime),
							php2JsTime(strtotime(date("Y-m-d",$etime)." 23:59"))
						);
						$idx++;
					}
				}else{
					if($etime < strtotime(date("Y-m-d",$etime)." 23:30")){
						$ret['events'][$idx][2]=php2JsTime($etime);
					}
				}
				continue;
			}
			
			$ret['books'][] = array(
				$row->Id,
				"Optaget",
				php2JsTime(mySql2PhpTime($row->StartTime)),
				php2JsTime(mySql2PhpTime($row->EndTime))
			);
			$idx++;
			//*/
		}
	}catch(Exception $e)
	{
		$ret['error'] = $e->getMessage();
	}

	$html='<table class="tableCalendar"><tbody>';
	$i=7;
	$j=1;
	$sw=1;
	$eidx=0;

	for(;$i<24;$i++,$j=1-$j){

		if(!$h2 AND isset($ret['events'][$eidx])){
			$r=$ret['events'][$eidx];
			$h1=substr($r[2],11,2)+0;	$m1=substr($r[2],14)+0;
			$h2=substr($r[3],11,2)+0;	$m2=substr($r[3],14)+0;
			$span=($h2-$h1)*2;
			if($m2==30 AND !$m1 OR $m1 AND !$m2)//add 1 for x:30 span
				$span++;
			elseif($m2==59)
				$span+=2;//end of day
			$eidx++;
		}
		
		$html.='<tr class="'.($j ? 'odd' : 'even').'">';

		if($j)//display time cell when odd loop
			$html.='<td'.($sw ? ' width="15%"' : '').' rowspan="2">
						<span>'.str_pad($i, 2, '0', STR_PAD_LEFT).':00</span>
					</td>';

		if($i==$h1){//start span
			if($j AND !$m1 OR !$j AND $m1)
				$html.='<td'.($sw ? ' width="85%"' : '').' rowspan="'.$span.'" class="bg-event">
<span class="red">'.$r[1].'</span>
					</td>';
			
			elseif($m1 AND $j)//when 1st half
				$html.='<td'.($sw ? ' width="85%"' : '').'><a class="bookable fancybox" onclick="return dobook(\''.$i.($j ? ':00' : ':30').'\')">tilgængelig</a></td>';
		}
		elseif($i<$h1 OR $i>=$h2 AND !$m2 AND $i!=23){//outside of span
			$html.='<td'.($sw ? ' width="85%"' : '').'><a class="bookable fancybox" onclick="return dobook(\''.$i.($j ? ':00' : ':30').'\')">tilgængelig</a></td>';
		}
		
		$html.='<td'.($sw ? ' width="0%"' : '').' class="td-hide"></td>';
		$html.='</tr>';
		
		if($i==$h2)
			$h2=NULL;

		if($sw)
			unset($sw);//only 1st row need set width

		if($j)
			$i--;//render 2 rows per hour, $i must delay each loop

	}
	
	$eidx=0;
	
	while(($r=$ret['books'][$eidx])){
		//get rid of booked time
		$h1=substr($r[2],11,2)+0;	$m1=substr($r[2],14)+0;
		
		if($m1){
			$html=preg_replace('#('.str_pad($h1, 2, '0', STR_PAD_LEFT).':00</span>)([\w\W]*?</tr>){3}#','$1</td><td></td><td class="td-hide"></td><tr class="even"><td rowspan="2" class="bg-event"><span class="red">Optaget</span></td><td class="td-hide"></td></tr><tr class="odd"><td rowspan="2"><span>'.str_pad($h1+1, 2, '0', STR_PAD_LEFT).':00</span></td><td class="td-hide"></td></tr>',$html);
		}
		else{
			$html=preg_replace('#('.str_pad($h1, 2, '0', STR_PAD_LEFT).':00</span>)([\w\W]*?</tr>){2}#','$1</td><td'.($h1==7 ? ' width="85%"' : '').' rowspan="2" class="bg-event"><span class="red">Optaget</span></td><td'.($h1==7 ? ' width="0%"' : '').' class="td-hide"></td></tr><tr class="even"><td class="td-hide"></td></tr>',$html);
		}
		
		$eidx++;
	}
	
	$html.='</tbody></table>';
	$ret['html']=$html;
	
	return $ret;
}

function listCalendar($day, $type){
  $phpTime = js2PhpTime($day);
  //echo $phpTime . "+" . $type;
  switch($type){
	case "month":
	  $st = mktime(0, 0, 0, date("m", $phpTime), 1, date("Y", $phpTime));
	  $et = mktime(0, 0, -1, date("m", $phpTime)+1, 1, date("Y", $phpTime));
	  break;
	case "week":
	  //suppose first day of a week is monday 
	  $monday  =  date("d", $phpTime) - date('N', $phpTime) + 1;
	  //echo date('N', $phpTime);
	  $st = mktime(0,0,0,date("m", $phpTime), $monday, date("Y", $phpTime));
	  $et = mktime(0,0,-1,date("m", $phpTime), $monday+7, date("Y", $phpTime));
	  break;
	case "day":
	  $st = mktime(0, 0, 0, date("m", $phpTime), date("d", $phpTime), date("Y", $phpTime));
	  $et = mktime(0, 0, -1, date("m", $phpTime), date("d", $phpTime)+1, date("Y", $phpTime));
	  break;
  }
  //echo $st . "--" . $et;
  return listCalendarByRange($st, $et);
}

function mlistCalendar($day, $type){
	$phpTime = js2PhpTime($day);

	$st = mktime(0, 0, 0, date("m", $phpTime), date("d", $phpTime), date("Y", $phpTime));
	$et = mktime(0, 0, -1, date("m", $phpTime), date("d", $phpTime)+1, date("Y", $phpTime));

  return mlistCalendarByRange($st, $et);
}

function updateCalendar($id, $st, $et){
  $ret = array();
  try{
	$db = new DBConnection();
	$db->getConnection();
	$sql = "update `jqcalendar` set"
	  . " `starttime`='" . php2MySqlTime(js2PhpTime($st)) . "', "
	  . " `endtime`='" . php2MySqlTime(js2PhpTime($et)) . "' "
	  . "where `id`=" . $id;
	//echo $sql;
		if(mysql_query($sql)==false){
	  $ret['IsSuccess'] = false;
	  $ret['Msg'] = mysql_error();
	}else{
	  $ret['IsSuccess'] = true;
	  $ret['Msg'] = 'Succefully';
	}
	}catch(Exception $e){
	 $ret['IsSuccess'] = false;
	 $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function updateDetailedCalendar($id, $st, $et, $sub, $ade, $dscr, $loc, $color, $tz){
  $ret = array();
  try{
	$db = new DBConnection();
	$db->getConnection();
	$sql = "update `jqcalendar` set"
	  . " `starttime`='" . php2MySqlTime(js2PhpTime($st)) . "', "
	  . " `endtime`='" . php2MySqlTime(js2PhpTime($et)) . "', "
	  . " `subject`='" . mysql_real_escape_string($sub) . "', "
	  . " `isalldayevent`='" . mysql_real_escape_string($ade) . "', "
	  . " `description`='" . mysql_real_escape_string($dscr) . "', "
	  . " `location`='" . mysql_real_escape_string($loc) . "', "
	  . " `color`='" . mysql_real_escape_string($color) . "' "
	  . "where `id`=" . $id;
	//echo $sql;
		if(mysql_query($sql)==false){
	  $ret['IsSuccess'] = false;
	  $ret['Msg'] = mysql_error();
	}else{
	  $ret['IsSuccess'] = true;
	  $ret['Msg'] = 'Succefully';
	}
	}catch(Exception $e){
	 $ret['IsSuccess'] = false;
	 $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function removeCalendar($id){
  $ret = array();
  try{
	$db = new DBConnection();
	$db->getConnection();
	$sql = "delete from `jqcalendar` where `id`=" . $id;
		if(mysql_query($sql)==false){
	  $ret['IsSuccess'] = false;
	  $ret['Msg'] = mysql_error();
	}else{
	  $ret['IsSuccess'] = true;
	  $ret['Msg'] = 'Succefully';
	}
	}catch(Exception $e){
	 $ret['IsSuccess'] = false;
	 $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}




header('Content-type:text/javascript;charset=UTF-8');
$method = $_GET["method"];
switch ($method) {
	case "add":
		$ret = addCalendar($_POST["CalendarStartTime"], $_POST["CalendarEndTime"], $_POST["CalendarTitle"], $_POST["IsAllDayEvent"]);
		break;
	case "list":
		$ret = listCalendar($_POST["showdate"], $_POST["viewtype"]);
		break;
	case "mlist":
		$ret = mlistCalendar($_POST["showdate"]);
		break;
	case "update":
		$ret = updateCalendar($_POST["calendarId"], $_POST["CalendarStartTime"], $_POST["CalendarEndTime"]);
		break; 
	case "remove":
		$ret = removeCalendar( $_POST["calendarId"]);
		break;
	case "adddetails":
		$st = $_POST["stpartdate"] . " " . $_POST["stparttime"];
		$et = $_POST["etpartdate"] . " " . $_POST["etparttime"];
		if(isset($_GET["id"])){
			$ret = updateDetailedCalendar($_GET["id"], $st, $et, 
				$_POST["Subject"], isset($_POST["IsAllDayEvent"])?1:0, $_POST["Description"], 
				$_POST["Location"], $_POST["colorvalue"], $_POST["timezone"]);
		}else{
			$ret = addDetailedCalendar($st, $et,					
				$_POST["Subject"], isset($_POST["IsAllDayEvent"])?1:0, $_POST["Description"], 
				$_POST["Location"], $_POST["colorvalue"], $_POST["timezone"]);
		}		
		break; 


}
echo json_encode($ret);